<template>
  <el-dialog
    title="鞋子信息录入"
    :visible="dialogVisible"
    width="95vw"
    center
    append-to-body
    style="background-color: rgba(0, 0, 0, 0.6); z-index: 2013"
    :before-close="handleClose"
  >
    <div style="display: flex">
      <div style="flex: 0 0 40vw">
        <el-form :inline="true" @submit.native.prevent="search">
          <el-form-item>
            <el-input
              ref="washCodeInput"
              placeholder="请扫码水洗码"
              v-model="washCode"
              id="washCode"
            >
              <template slot="append">
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  @click="search"
                ></el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="photography"
              v-if="shoeDetail.length"
              >拍照</el-button
            >

            <el-button type="primary" @click="handleComplete"
              >拍摄完成</el-button
            >
          </el-form-item>
        </el-form>

        <el-table :data="shoeDetail">
          <el-table-column property="washCode" label="水洗码"></el-table-column>
          <el-table-column property="washType" label="类型"></el-table-column>
          <el-table-column property="srgCode" label="货架号"></el-table-column>
          <el-table-column property="srgCode" label="图片" width="240">
            <template slot-scope="scope" v-if="scope.row.picture">
              <div class="image-box">
                <div
                  class="image-item"
                  v-for="(item, index) in scope.row.picture"
                >
                  <i
                    class="el-icon-error"
                    @click="deleteImage(scope.$index, index)"
                  />
                  <el-image
                    style="width: 50px; height: 50px; margin-right: 5px"
                    :src="item.url"
                    :preview-src-list="
                      scope.row.picture.map((item) => item.url)
                    "
                  >
                  </el-image>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column property="srgCode" label="操作" width="80">
            <template slot-scope="scope" v-if="scope.row.washCode === washCode">
              <el-button size="small" type="primary" @click="handleUploadImage"
                >上传</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div style="flex: 1">
        <CameraCaptureTask
          v-if="cameraCaptureVisible"
          ref="cameraCaptureTask"
          @success="success"
          @close="cameraCaptureVisible = false"
        />
      </div>
    </div>
  </el-dialog>
</template>

<script>
import CameraCaptureTask from "@/components/CameraCaptureTask/CameraCaptureTask.vue";
import { v4 as uuidv4 } from "uuid";
import { base64DataToFile } from "@/utils/file";
import { getOssClient } from "../../../../utils/tool";
import dayjs from "dayjs";
export default {
  props: ["photographVisible", "detail"],
  components: {
    CameraCaptureTask,
  },
  data() {
    return {
      dialogVisible: false,
      washCode: "",
      shoeDetail: [],

      cameraCaptureVisible: false,
    };
  },
  watch: {
    photographVisible(val) {
      this.$nextTick(() => {
        this.washCode = "";
        this.dialogVisible = val;
        this.shoeDetail = [];
      });
    },
    dialogVisible(val) {
      if (val) {
        this.$nextTick(() => {
          this.$refs.washCodeInput.focus();
        });
      }
    },
  },
  created() {
    document.addEventListener("keydown", this.physicalPhotography);
  },
  destroyed() {
    document.removeEventListener("keydown", this.physicalPhotography);
  },
  methods: {
    photography() {
      this.$refs.cameraCaptureTask.photograph();
    },
    physicalPhotography(event) {
      if (event.key === "F3") {
        event.preventDefault();
        event.stopPropagation();
        if (
          !this.shoeDetail.length ||
          !this.shoeDetail.find(
            (item) =>
              this.washCode ||
              this.shoeDetail[this.shoeDetail.length - 1].washCode
          )
        ) {
          return;
        }
        this.$refs.cameraCaptureTask.photograph();
      }
    },

    handleClose() {
      this.$emit("close");
    },
    search() {
      if (!this.washCode) {
        this.$message.error("请输入水洗码");
        return;
      }
      const ids = this.detail.shoePoList.map((item) => item.washCode);
      if (!ids.includes(this.washCode)) {
        this.$message.error("该水洗码不在订单中");
        return;
      }
      if (this.shoeDetail.find((item) => item.washCode === this.washCode)) {
        this.$message.error("该水洗码已录入");
        return;
      }

      const item = this.detail.shoePoList.find(
        (item) => item.washCode === this.washCode
      );
      this.shoeDetail = [
        ...this.shoeDetail,
        {
          ...item,
          picture: [...item.picture],
        },
      ];
      this.cameraCaptureVisible = true;
    },
    success(photos) {
      const shoeDetail = this.shoeDetail.find(
        (item) =>
          item.washCode ===
          (this.washCode ||
            this.shoeDetail[this.shoeDetail.length - 1].washCode)
      );
      const uploadList = [];
      photos.forEach((item) => {
        const uuid = uuidv4();
        shoeDetail.picture.push({
          url: item,
          data: null,
          status: "upload",
          uuid,
        });

        uploadList.push({
          url: item,
          washCode: shoeDetail.washCode,
          uuid,
        });
      });

      this.uploadImage(uploadList);
      this.washCode = "";
      this.$refs.washCodeInput.focus();
    },

    async uploadImage(waitUploadImageList) {
      try {
        const client = await getOssClient();

        // 等待上传的图片
        const requestList = waitUploadImageList.map((item) => {
          const fileName = `public/img/${dayjs().format(
            "YYYY-MM-DD"
          )}/${uuidv4()}.png`;
          item.efficient = fileName;
          return client.put(fileName, base64DataToFile(item.url));
        });

        const resultList = await Promise.all(requestList);

        resultList.forEach((res, index) => {
          const imageObject = waitUploadImageList[index];
          // 对应鞋子
          const shoeIndex = this.shoeDetail.findIndex(
            (item) => item.washCode === imageObject.washCode
          );
          if (shoeIndex === -1) {
            return;
          }

          // 对应索引
          const shoePitureIndex = this.shoeDetail[shoeIndex].picture.findIndex(
            (item) => item.uuid === imageObject.uuid
          );

          if (shoePitureIndex === -1) {
            return;
          }
          // 改变图片状态
          this.shoeDetail[shoeIndex].picture.splice(shoePitureIndex, 1, {
            url: this.shoeDetail[shoeIndex].picture[shoePitureIndex].url,
            data: waitUploadImageList[index].efficient,
            status: "success",
            uuid: uuidv4(),
          });
          this.shoeDetail = [...this.shoeDetail];
        });
      } catch (error) {
        console.error(error);
      }
    },

    handleComplete() {
      this.$emit("success", this.shoeDetail);
      this.dialogVisible = false;
      this.washCode = "";
      this.shoeDetail = [];
      this.cameraCaptureVisible = false;
    },

    deleteImage(scopeIndex, index) {
      this.shoeDetail[scopeIndex].picture.splice(index, 1);
      if (this.shoeDetail[scopeIndex].picture.length === 0) {
        this.shoeDetail.splice(scopeIndex, 1);
        if (this.washCode === this.shoeDetail[index].washCode) {
          this.washCode = "";
        }
      }
    },
    handleUploadImage() {
      /**
       * 创建input 批量上传图片
       */
      const input = document.createElement("input");
      input.type = "file";
      input.accept = "image/*";
      input.multiple = true;
      input.onchange = (e) => {
        const files = e.target.files;
        const uploadList = [];
        for (let i = 0; i < files.length; i++) {
          const file = files[i];
          const reader = new FileReader();
          reader.onload = (e) => {
            const url = e.target.result;
            const uuid = uuidv4();
            const shoeDetail = this.shoeDetail.find(
              (item) => item.washCode === this.washCode
            );
            shoeDetail.picture.push({
              url,
              data: null,
              status: "upload",
              uuid,
            });
            uploadList.push({
              url,
              washCode: this.washCode,
              uuid,
            });
          };
          reader.readAsDataURL(file);
        }
        this.uploadImage(uploadList);
      };
      input.click();
    },
  },
};
</script>

<style lang="scss" scoped>
.image-box {
  width: 220px;
  display: flex;
  flex-wrap: wrap;
  .image-item {
    position: relative;
    flex: 0 0 50px;
    &:nth-child(4n) {
      margin-right: 0;
    }
    .el-icon-error {
      position: absolute;
      right: 0;
      top: 0;
      z-index: 1;
      background-color: #ffffff;
      border-radius: 50%;
      cursor: pointer;
    }
  }
}
</style>
